package cn.jvtc.course.management.system.dao.impl;

import cn.jvtc.course.management.system.bean.TeacherInfoDO;
import cn.jvtc.course.management.system.exception.TeacherDaoException;
import cn.jvtc.course.management.system.utils.JdbcUtils;

import java.sql.*;

/**
 * 用于操作数据库的教师表
 *
 * @author GaoFeng2017
 * @date 2017-12-11 18:53:24
 **/

public class TeacherDaoImpl {
    /**
     * @description:
     * @author: GaoFeng2017
     * @date: 2017/12/11 18:54
     * @param: [teacherInfoDO]
     * @return: boolean
     *
     */
    public boolean addTeacher(TeacherInfoDO teacherInfoDO) {
        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        int i = 0;
        String sql = "insert into teacher_info(gmt_create,name,sex,department,permission_code,number,password) values(?,?,?,?,?,?,?)";

        try{
            con = JdbcUtils.getConnection();
            st = con.prepareStatement(sql);
            st.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
            st.setString(2,teacherInfoDO.getName());
            st.setString(3,teacherInfoDO.getSex());
            st.setString(4,teacherInfoDO.getDepartment());
            st.setByte(5,teacherInfoDO.getPermissionCode());
            st.setLong(6,teacherInfoDO.getNumber());
            st.setString(7,teacherInfoDO.getPassword());
            i = st.executeUpdate();
        } catch(Exception e) {
            throw new TeacherDaoException(e);
        } finally {
            JdbcUtils.releaseResource(con,st,rs);
        }

        if(i <= 0) {
            return false;
        }
        return true;
    }

    /**
     * 根据姓名和部门获取老师id,临时使用
     * @description:
     * @author: GaoFeng2017
     * @date: 2017/12/11 22:50
     * @param: [name, department]
     * @return: long
     *
     */
    public long getId(String name,String department) {

        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        String sql = "select id from teacher_info where name = ? and department = ?";
        long id = 0;
        try{
            con = JdbcUtils.getConnection();
            st = con.prepareStatement(sql);
            st.setString(1, name);
            st.setString(2,department);
            rs = st.executeQuery();
            if(rs.next()) {
                id = rs.getLong("id");
            }

        } catch(Exception e) {
            throw new TeacherDaoException(e);
        } finally {
            JdbcUtils.releaseResource(con,st,rs);
        }

        return id;
    }
}
